package net.wofly.cashier.order.web;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.wofly.cashier.order.domain.Order;
import net.wofly.cashier.order.domain.OrderContent;
import net.wofly.cashier.order.service.ICashierOrderService;
import net.wofly.cashier.order.validator.OrderValidator;
import net.wofly.cashier.table.domain.Table;
import net.wofly.common.web.BaseController;
import net.wofly.framework.util.ResultCode;
import net.wofly.framework.util.ReturnBean;

/**
 * Created by LiuJianbo on 2017/10/21.
 */
@Controller
@RequestMapping(value = "/api/cashierOrder")
@Api(description = "订单管理（酒店模块）")
public class CashierOrderController extends BaseController {
    
    Logger logger = LoggerFactory.getLogger(CashierOrderController.class);
    
    @Autowired
    ICashierOrderService iCashierOrderService;
    
    /**
     * 加菜
     * <ul>
     * <li>加菜是判断当前订单的状态</li>
     * <li>加菜时要判断当前是否为结账状态，如果未结账则将订单状态修改为加菜状态，同时增加加菜时间；如果己结账，则将订单状态修改为加菜未结账状态</li>
     * <li>判断所加菜是否有库存，有库存加菜才能成功。加菜成功的同时减去相应的库存</li>
     * <li>加菜没有库存时，提示用户</li>
     * <li>当没有任何加菜成功时，不修改当前订单的状态</li>
     * </ul>
     *
     * @param orderID
     * @param orderContents
     */
    @ApiOperation(value = "加菜")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderID", value = "订单ID，已经点完菜的订单，即加载哪个订单上", required = true,
            dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "orderContents", value = "加菜内容，菜品列表", required = true, dataType = "array")})
    @RequestMapping(value = "/addDish", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<Order> addDish(String orderID, @RequestBody String orderContents) {
        ReturnBean<Order> returnBean;
        List<OrderContent> contents = JSON.parseArray(orderContents, OrderContent.class);
        String errorMessage = OrderValidator.validateAddDishedParam(orderID, contents);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<Order>(-1, errorMessage);
        } else {
            returnBean = iCashierOrderService.addDish(orderID, contents);
        }
        return returnBean;
    }
    
    /**
     * 收桌
     * <ul>
     * <li>将当前桌子恢复为空闲状态</li>
     * <li></li>
     * </ul>
     *
     * @param tableID
     */
    @ApiOperation(value = "收桌")
    @ApiImplicitParams({@ApiImplicitParam(name = "tableID", value = "餐桌ID", required = true, paramType = "form")})
    @RequestMapping(value = "/cleanTable", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<String> cleanTable(String tableID) {
        ReturnBean<String> returnBean;
        String errorMessage = OrderValidator.validateTableID(tableID);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            iCashierOrderService.cleanTable(tableID);
            returnBean = new ReturnBean<>(ResultCode.SUCCESS, "收桌成功");
        }
        return returnBean;
    }
    
    /**
     * 开台
     * <ul>
     * <li>新开一个餐桌</li>
     * <li>验证当前餐桌是否有预约或预购</li>
     * <li></li>
     * </ul>
     *
     * @param tableID
     */
    @ApiOperation(value = "开台")
    @ApiImplicitParams({@ApiImplicitParam(name = "tableID", value = "餐桌ID", required = true, paramType = "form")})
    @RequestMapping(value = "/openTable", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<Table> openTable(String tableID) {
        ReturnBean<Table> returnBean;
        String errorMessage = OrderValidator.validateTableID(tableID);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            iCashierOrderService.openTable(tableID);
            returnBean = new ReturnBean<>(ResultCode.SUCCESS, "开台成功");
        }
        return returnBean;
    }
    
    /**
     * 结账
     * <ul>
     * <li>判断当前订单状态</li>
     * <li>计算计算中所有未结账的菜品总额与前端传递过来金额进行核实，如果相等则进行后一步支付；如果不等时，提示用户</li>
     * <li></li>
     * </ul>
     *
     * @param orderID
     * @param payType
     * @param sum
     * @param payAccount
     */
    @ApiOperation(value = "结账")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderID", value = "订单ID", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "payType", value = "支付类型", required = true, dataType = "Integer", paramType = "form"),
            @ApiImplicitParam(name = "sum", value = "支付金额", required = true, dataType = "Integer", paramType = "form"),
            @ApiImplicitParam(name = "payAccount", value = "支付账号", required = true, dataType = "String", paramType = "form")})
    @RequestMapping(value = "/pay", method = {RequestMethod.POST})
    @ResponseBody
    public String pay(String orderID, Integer payType, Integer sum, String payAccount ,HttpServletResponse response) throws IOException,
            AlipayApiException {
        Map<String ,Object> map = new HashMap<>();
        ReturnBean returnBean;
        String errorMessage = OrderValidator.validatePayParams(orderID, payType, sum, payAccount);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<>(-1, errorMessage);
        } else {
            //returnBean = new ReturnBean(ResultCode.SUCCESS, "调用接口成功",
              //      iCashierOrderService.pay(orderID, payType, sum, payAccount));
            //response.getWriter().write(returnBean.getResult().toString());
            //map.put("result",returnBean.getResult());
        }
        //return returnBean.getResult().toString();
        return null;
        //return map;
    }
    
    /**
     * 下单
     * <ul>
     * <li>新增一个订单</li>
     * <li>同时修改订单所在餐桌的状态</li>
     * <li>判断每一个菜当前有库存。没有库存的提示用户，有库存的直接下单</li>
     * <li>下单成功的同时，减去对应的菜品库存</li>
     * </ul>
     *
     * @param order
     */
    @ApiOperation(value = "下单")
    @ApiImplicitParams({@ApiImplicitParam(name = "order", value = "订单实体", required = true, dataType = "Order")})
    @RequestMapping(value = "/placeOrder", method = {RequestMethod.POST})
    @ResponseBody
    public ReturnBean<Order> placeOrder(@RequestBody Order order) {
        ReturnBean<Order> returnBean;
        String errorMessage = OrderValidator.validatePlaceOrderParam(order);
        if (errorMessage.length() > 0) {
            returnBean = new ReturnBean<Order>(-1, errorMessage);
        } else {
            returnBean = iCashierOrderService.placeOrder(order, 0);
        }
        return returnBean;
    }
    
    @RequestMapping(value = "/notify4AliPay", method = {RequestMethod.POST})
    @ResponseBody
    public String notify4AliPay() {
        logger.info(">>> notify4AliPay 支付宝支付成功， 执行回调函数");
        
        //TODO 执行处理逻辑
        return "success";
    }
    
    
    @RequestMapping(value = "/orderPay", method = {RequestMethod.GET})
    public ModelAndView orderPay() {
        logger.info(">>> 进入支付宝支付页面，进行支付");
        return new ModelAndView("pay");
    }
    
    @RequestMapping(value = "/success", method = {RequestMethod.GET})
    public ModelAndView paySuccess() {
        logger.info(">>> 支付 成功");
        return new ModelAndView("paySuccess");
    }
    
    @RequestMapping(value = "/order", method = {RequestMethod.GET})
    public ModelAndView order() {
        logger.info(">>> 进入订单页面 ");
        return new ModelAndView("order");
    }
    
    @RequestMapping(value = "/order1", method = {RequestMethod.GET,RequestMethod.POST})
    public String order1() {
        logger.info(">>> 进入订单页面1 ");
        return "order1";
    }
   
}
